$(function(){
    /*-- 富文本编辑器 --------------------------------------------*/
    Simditor.locale = 'zh-CN';
    let editor = new Simditor({
        textarea: $('#editor'),//textarea的id
        placeholder: '这里输入文字...',
        toolbar: ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color','ol', 'ul', 'blockquote', 'code', 'table', 'link', 'image', 'hr','indent', 'outdent', 'alignment'], //工具条都包含哪些内容
        pasteImage: true,// 不允许粘贴图片
        upload : {
            url: '/file/richtext_img_upload.do', //文件上传的接口地址
            params: null, //键值对,指定文件上传接口的额外参数,上传的时候随文件一起提交
            fileKey: 'upload_file', //服务器端获取文件数据的参数名
            connectionCount: 1,
            leaveConfirm: '正在上传图片'
        }
    });
    /*----------------------------------------------*/
    // 表单 obj
    let objItemInfo = {
            projectno : '',
            projectname : '',
            team : '',
            projecttype : '',
            projectgrade : '',
            addprojectstuname : '',
            instructor : '',
            getprize : '',
            projectdetailed : '',
            evidenceid : '',
            evidenceillustrate : '',
            evidenceurl : '',
            coverurl : ''
        },

        activeMenuItem_ID = 0;// 选中项目的ID

    // 附件描述信息
    let oFilesInfo = {
        aUrl : [],
        aFiles : [],
        aInfo : [],
        aFilesName : []
    };

    initPage();// 页面初始化
    /*********************************************/

    // 获取项目信息
    $('#myItemList').on('click','a',function () {
        // 当前项目 ID
        let thisID = $(this).attr('data-id');
        $(this).addClass('active').siblings().removeClass('active');
        if( thisID != activeMenuItem_ID ){
            // 重置表格基本信息
            resetForm(true);

            activeMenuItem_ID = thisID;

            // 删除附件缓存
            removeFiles_OBJ();

            // 获取项目详情
            let itemInfo = new Promise( (resolve, reject)=> {
                // 发送请求
                $.ajax({
                    url: '/projectDetails/details_productt.do',
                    data: {
                        projectno : activeMenuItem_ID
                    },
                    dataType: 'json',
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function (data) {
                        console.log(data);
                        if (data.status == 0) {
                            resolve(data);
                            return false;
                        } else {
                            reject(data);
                            return false;
                        }
                    }
                });
            });
            itemInfo.then( (data)=>{

                let info = data.data;
                objItemInfo.projectno = thisID;
                objItemInfo.projectname = info.projectname;
                objItemInfo.team = info.team;
                objItemInfo.projecttype = info.projecttype;
                objItemInfo.projectgrade = info.projectgrade;
                objItemInfo.addprojectstuname = info.addprojectstuname;
                objItemInfo.instructor = info.instructor;
                objItemInfo.getprize = info.getprize;
                objItemInfo.projectdetailed = info.projectdetailed;
                objItemInfo.evidenceid = info.evidenceid;
                objItemInfo.evidenceillustrate = info.evidenceillustrate;
                objItemInfo.evidenceurl = info.evidenceurl;
                objItemInfo.coverurl =  info.coverurl;

                // 插入项目信息
                $('#itemName').val( objItemInfo.projectname );// 项目名称
                $('#teamName').val( objItemInfo.team );// 团队名称
                $('#addprojectstuname').val( objItemInfo.addprojectstuname );// 参赛学生
                $('#instructor').val( objItemInfo.instructor );// 指导老师
                $('#projecttype').val( objItemInfo.projecttype);// 申报类型
                $('#getprize').val( objItemInfo.getprize);// 获奖情况
                editor.setValue( objItemInfo.projectdetailed );// 富文本
                $('#projectgrade').val( objItemInfo.projectgrade);// 项目级别

                // 封面图片
                $('#iconImgPanel').attr( 'src', objItemInfo.coverurl );

                // 附件渲染
                if( objItemInfo.evidenceid != '' ){
                    // 附件描述信息
                    let aName =  objItemInfo.evidenceid.split('|');
                    let aUrl = objItemInfo.evidenceurl.split('|');
                    let aInfo = objItemInfo.evidenceillustrate.split('|');

                    for( let i=0; i<aName.length; i++ ){
                        oFilesInfo.aFilesName.push( aName[i] );
                        oFilesInfo.aUrl.push( aUrl[i] );
                        oFilesInfo.aInfo.push( aInfo[i] );
                    }

                    for(let i=0; i<oFilesInfo.aFilesName.length; i++){
                        let DOM = $('<li>' +
                                        '<strong>说明:</strong>' +
                                        '<a href="'+ oFilesInfo.aUrl[i] +'" class="mar-10 mar-l" style="margin-top: 0">'+oFilesInfo.aFilesName[i]+'</a>' +
                                        '<p>'+oFilesInfo.aInfo[i]+'</p>' +
                                        '<button type="button" class="btn btn-danger btn-sm">删除</button>' +
                                    '</li>');
                        DOM.appendTo( $('#filesList_box') );
                    }
                }
            } ).catch( (data)=>{
                if( data.status == 10 ){
                    spop_waring( data.msg, function () {}, outLoing );
                }
            } ) ;
        }else{
            return console.log('当前项目');
        }
    });

    // 申报新项目
    $('#addNesMy-item').on('click',function(){
        // 样式重置
        resetForm( false );

        // 删除附件缓存
        removeFiles_OBJ();

        // 表单信息重置
        objItemInfo.projectno = '';
        objItemInfo.projectname = '';
        objItemInfo.team = '';
        objItemInfo.projecttype = '';
        objItemInfo.projectgrade = '';
        objItemInfo.addprojectstuname = '';
        objItemInfo.instructor = '';
        objItemInfo.getprize = '';
        objItemInfo.projectdetailed = '';
        objItemInfo.evidenceid = '';
        objItemInfo.evidenceillustrate = '';
        objItemInfo.evidenceurl = '';
        objItemInfo.coverurl = '';

        // 封面图片
        $('#iconImgPanel').attr('src','images/timg_r2_c2.jpg');
    });

    // 添加 or 修改 <申报>
    $('#submit-shenBao').on('click',function(){
        mask_open();
        // 修改
        if( objItemInfo.projectno != '' ){
            console.log('xxx');
            // 封面图片
            let upIconImg = new Promise( (resolve, reject)=>{
                if( $('#iconImg-input')[0].files.length == 0 ){
                    resolve( false );
                    return false;
                }

                let formData = new FormData();
                formData.append( 'upload_file[]', $('#iconImg-input')[0].files[0] );
                // 上传文件
                $.ajax({
                    url : '/file/upload.do',
                    type : 'post',
                    data : formData,
                    xhrFields : {
                        withCredentials: true
                    },
                    crossDomain: true,
                    cache:false,
                    contentType: false,// 使jq不要去设置Content-Type请求头
                    processData: false,// 使jq不要去处理发送的数据
                    success : function (data) {
                        if( data.status == 0 ){
                            resolve( data );
                        }else{
                            reject( data );
                        }
                    }
                });
            } );
            let upFiles = new Promise( (resolve, reject)=>{
                if( oFilesInfo.aFiles.length == 0 ){
                    resolve( false );
                    return;
                }

                let formData = new FormData();
                for(let i=0; i<oFilesInfo.aFiles.length; i++ ) {
                    formData.append('upload_file[]', oFilesInfo.aFiles[i]);
                }

                // 发送请求
                $.ajax({
                    url : '/file/upload.do',
                    type : 'post',
                    data : formData,
                    xhrFields : {
                        withCredentials: true
                    },
                    crossDomain: true,
                    cache:false,
                    contentType: false,// 使jq不要去设置Content-Type请求头
                    processData: false,// 使jq不要去处理发送的数据
                    success : function (data) {
                        if( data.status == 0 ){
                            resolve( data.data );
                        }else{
                            reject( data );
                        }
                    }
                });
            } );

            let addFiles2 = Promise.all( [upIconImg, upFiles] );
            addFiles2.then( (aData)=>{
                addItemAjax(aData, mask_close);
            } ).catch( (data)=>{
                if( data.status == 10  ){
                    spop_waring( data.msg, mask_close, outLoing );
                }else{
                    spop_er(data.msg);
                }
            } );
        }
        // 添加
        else{

            // 版面图片上传
            let upIconImg = new Promise( (resolve, reject)=>{
                if( $('#iconImg-input')[0].files.length == 0 ){
                    reject( '未选中封面图片' );
                    return false;
                }else{
                    let formData = new FormData();
                    formData.append( 'upload_file[]', $('#iconImg-input')[0].files[0] );
                    // 上传文件
                    $.ajax({
                        url : '/file/upload.do',
                        type : 'post',
                        data : formData,
                        xhrFields : {
                            withCredentials: true
                        },
                        crossDomain: true,
                        cache:false,
                        contentType: false,// 使jq不要去设置Content-Type请求头
                        processData: false,// 使jq不要去处理发送的数据
                        success : function (data) {
                            console.log(data);
                            if( data.status == 0 ){
                                resolve( data );
                            }else{
                                reject( data );
                            }
                        }
                    });
                }
            } );
            // 附件上传
            let upFile = new Promise( (resolve, reject)=>{
                if( oFilesInfo.aFiles.length == 0 ){
                    resolve( null );
                    return;
                }

                let formData = new FormData();
                for(let i=0; i<oFilesInfo.aFiles.length; i++ ){
                    formData.append('upload_file[]', oFilesInfo.aFiles[i]);
                }
                // 发送请求
                $.ajax({
                    url : '/file/upload.do',
                    type : 'post',
                    data : formData,
                    xhrFields : {
                        withCredentials: true
                    },
                    crossDomain: true,
                    cache:false,
                    contentType: false,// 使jq不要去设置Content-Type请求头
                    processData: false,// 使jq不要去处理发送的数据
                    success : function (data) {
                        console.log(data);
                        if( data.status == 0 ){
                            resolve( data.data );
                        }else{
                            reject( data );
                        }
                    }
                });
            } );

            let allFiles = Promise.all( [upIconImg, upFile] );
            allFiles.then( (aData)=>{
                // 提交项目
                addItemAjax( aData , mask_close);
            } ).catch( (data)=>{
                if( data.status == 10 ){
                    spop_waring( data.msg, mask_close , outLoing );
                }else{
                    spop_er('添加失败', mask_close);
                }
            } );
        }

        // 提交项目
        function addItemAjax( aData, callBack) {
            let sUpTitleImg = '';// 封面图片
            let aUpFilesUri = '';// 附件

            // 封面
            if( aData[0] ){
                sUpTitleImg = aData[0].data[0].uri;
            }else{
                // 原来的图片
                sUpTitleImg = objItemInfo.coverurl;
            }
            // 附件
            if( aData[1] ){
                aUpFilesUri = aData[1];
                for(let i=0; i<aUpFilesUri.length; i++){
                    oFilesInfo.aUrl.push( aUpFilesUri[i].uri );
                }
            }

            console.log('---------------------');
            console.log(oFilesInfo.aFilesName);
            console.log(oFilesInfo.aFiles);
            console.log(oFilesInfo.aUrl);
            console.log('---------------------');
            objItemInfo.evidenceid = oFilesInfo.aFilesName.join('|');
            objItemInfo.evidenceurl = oFilesInfo.aUrl.join('|');
            objItemInfo.evidenceillustrate = oFilesInfo.aInfo.join('|');

            objItemInfo.coverurl = sUpTitleImg;
            objItemInfo.projectdetailed = editor.getValue();
            objItemInfo.projectname = $('#itemName').val();
            objItemInfo.team = $('#teamName').val();
            objItemInfo.projecttype = $('#projecttype').val();
            objItemInfo.projectgrade = $('#projectgrade').val();
            objItemInfo.addprojectstuname = $('#addprojectstuname').val();
            objItemInfo.instructor = $('#instructor').val();
            objItemInfo.getprize = $('#getprize').val();
            // 发送请求
            $.ajax({
                url : '/projectDetails/save.do',
                data : objItemInfo,
                type : 'post',
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function ( data ) {
                    if( data.status == 0 ){
                        spop_ok( data.msg, initPage ,function () {});
                    }else if( data.status == 10 ){
                        spop_waring( data.msg, mask_close, outLoing);
                    }else{
                        spop_er( data.msg );
                    }

                    if( typeof callBack=='function'){
                        callBack();
                    }
                }
            });

        }
    });

    // 添加图片
    $('#iconImg-input').on('change',function () {
        $('#iconImgPanel').attr('src', getObjectURL($(this)[0].files[0]));
    });
    // 增加附件按钮
    $('#addFilesBtn').on('click', function(){
        let en_addFiles = $('#addFiles')[0].files[0];
        let en_addFilesInfo = $('#addFilesInfo').val().trim();

        if( en_addFiles ){
            oFilesInfo.aInfo.push( en_addFilesInfo);// 添加到描述列表
            oFilesInfo.aFiles.push( en_addFiles );// 添加到文件列表
            oFilesInfo.aFilesName.push( en_addFiles.name );// 文件名

            // 获取本地文件地址
            let url = getObjectURL( en_addFiles );
            // 动态添加文件;
            let DOM = $('<li>' +
                            '<strong>说明:</strong>' +
                            '<a href="'+ url +'">'+ en_addFiles.name +'</a>' +
                            '<p>'+ en_addFilesInfo +'</p>' +
                            '<button type="button" class="btn btn-danger btn-sm">删除</button>' +
                        '</li>');
            $('#filesList_box').append(DOM);
        }else{
            spop_waring('请选择附件后操作');
            return false;
        }

        // 清空原有数据
        $('#addFiles').val('');
        $('.addFilesBox').find('label').html( $('<span class="text-right pad-10 pad-r"> 添加文件 <i class="glyphicon glyphicon-share"></i></span>'));
        $('#addFilesInfo').val('');
    });
    $('#addFiles').on('change',function () {
        let files = $(this)[0].files[0];
        if( files ){
            $('.addFilesBox').find('label').html( $('<span class="text-right pad-10 pad-r">'+ files.name +'</span>') );
        }else{
            $('.addFilesBox').find('label').html( $('<span class="text-right pad-10 pad-r"> 添加文件 <i class="glyphicon glyphicon-share"></i></span>') );
        }
    });
    // 删除附件
    $('#filesList_box').on('click','button',function(){
        let DOM = $(this).parents('li')[0];
        let INDEX = $('#filesList_box').children('li').index( DOM );
        let aSon = $('#filesList_box').children('li').length;

        oFilesInfo.aFiles.splice( INDEX, 1 );
        oFilesInfo.aInfo.splice( INDEX, 1 );
        oFilesInfo.aFilesName.splice( INDEX, 1);
        DOM.remove();

        if( aSon == 1 ){
            $('#filesList_box').append('<li><h5>暂无附件</h5></li>');
        }
    });
    // 页面初始化
    function initPage(){
        mask_open();

        // 获取我的项目列表
        let getMyItemList = new Promise( (resolve, reject) =>  {
            $.ajax({
                url : '/projectDetails/list_my_product.do',
                type:'post',
                data : {},
                dataType : 'json',
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if( data.status == 0){
                        resolve( data );
                    }else {
                        reject( data );
                        return false;
                    }
                }
            });
        } );
        // 获取所有项目级别列表
        let getItemRank = new Promise( (resolve, reject) => {
            $.ajax({
                url : '/projectGrade/list.do',
                type:'post',
                data : {},
                dataType : 'json',
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if(data.status == 0){
                        resolve( data );
                    }else {
                        reject( data );
                        return false;
                    }
                }
            });
        } );
        // 获取所有申报类型
        let getItemType = new Promise( (resolve, reject) => {
            $.ajax({
                url : '/manage/racetype/get_raceType.do',
                type:'post',
                data : {parentId:0},
                dataType : 'json',
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success: function (data) {
                    if(data.status == 0){
                        resolve( data );
                    }else {
                        reject( data );
                        return false;
                    }
                }
            });
        } );

        let pageInitData = Promise.all( [ getMyItemList, getItemRank, getItemType ] );
        pageInitData.then( (data) => {
            let aMyItem = data[0].data,// 获取我的项目列表
                aItemRank = data[1].data,// 获取所有项目级别列表
                aItemType_header = data[2].data;// 获取所有申报类型

            // 渲染申报项目类型
            getSonType(aItemType_header);

            // 渲染项目级别
            $('#projectgrade').html('');
            for(let i=0; i<aItemRank.length; i++){
                $('#projectgrade').append($('<option value="'+ aItemRank[i] +'">'+ aItemRank[i] +'</option>'));
            }

            // 渲染我的项目
            setMyItemList( aMyItem ,function () {
                $('#myItemList').find('a:first-child').click();

                $(document).scrollTop(0);
            });

            // 关闭蒙版
            mask_close();
        } ).catch( (data)=>{
            mask_close();
            if( data.status ==10 ){
                spop_waring( data.msg, function () {}, outLoing );
            }else{
                spop_er(data.msg);
            }
        } );

    }
    // 样式重置
    function resetForm( OFF ) {
        // 当前ID
        activeMenuItem_ID = '';

        $('#addItemForm')[0].reset();
        $('#filesList_box').html(''); // 附件div
        $('#iconImg-input').val('');
        if( OFF ){
            $('.TitleChangeInfo').html('项目详情'); // 表头
            $('#submit-shenBao').removeClass('btn-info').addClass('btn-primary').html('保存');// 按钮
            $('#addNesMy-item').attr('disabled',false);
        }else{
            // 样式重置
            $('.TitleChangeInfo').html('申报新项目');
            $('#submit-shenBao').addClass('btn-info').removeClass('btn-primary').html('提交');
            $('#addNesMy-item').attr('disabled','disabled');
            $('#myItemList').children('a').removeClass('active');
        }
    }
    // 清除附件缓存
    function removeFiles_OBJ() {
        oFilesInfo.aUrl.splice(0, oFilesInfo.aUrl.length);
        oFilesInfo.aInfo.splice(0, oFilesInfo.aInfo.length);
        oFilesInfo.aFiles.splice(0, oFilesInfo.aFiles.length);
        oFilesInfo.aFilesName.splice(0, oFilesInfo.aFilesName.length);
    }
    // 渲染我的项目
    function setMyItemList( aData, callBack  ) {
        let myItemList = $('#myItemList');
        myItemList.html('');
        if( Number( aData.length ) ){
            for(let i=0; i<aData.length; i++){
                let DOM = $('<a href="#" class="list-group-item Po-r" data-id="'+ aData[i].projectno +'">' +
                    '<p style="font-size: 16px" class="Text-ovh">'+ aData[i].projectname +'</p>' +
                    '<p class="mar-0">申报时间: <span>'+ aData[i].creattime +'</span> </p>' +
                    '<i class="glyphicon glyphicon-menu-right Po-a"></i>' +
                    '</a>');
                DOM.prependTo( myItemList );
            }
        }else{
            $('<div class="pad-10 text-center">' +
                '<h5>暂无项目</h5>' +
                '</div>').prependTo( myItemList );
        }
        if( typeof callBack == 'function' && Number( aData.length ) ){
            callBack();
        }
    }
    // 渲染项目类型
    function getSonType(itemType_header) {
        let itemType_son = [];
        console.log(itemType_header);
        for(let i=0;i<itemType_header.length;i++){
            // 获取每个子项目类型
            itemType_son[i] = new Promise((resolve, reject) => {
                $.ajax({
                    url : '/manage/racetype/get_raceType.do',
                    type:'post',
                    data : {
                        parentId : itemType_header[i].racetypeno
                    },
                    dataType : 'json',
                    xhrFields : {
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function (data) {
                        if(data.status == 0){
                            resolve( data );
                        }else {
                            reject( data );
                        }
                    }
                });
            });
        }
        let itemSon = Promise.all( itemType_son );
        itemSon.then( (data)=>{
            setItemType(data);
        }).catch( (data)=>{
            if( data.status == 10 ){
                spop_waring(data.msg, function () {}, outLoing );
            }
        } );

        // 渲染子项目类型
        function setItemType(data) {
            $('#projecttype').html('');
            // 头
            for(let i=0; i<itemType_header.length; i++){
                let selectDOM = $('<optgroup label="'+ itemType_header[i].racetype +'"></optgroup>');
                // son
                for(let j=0; j<data[i].data.length; j++){
                    let info = data[i].data;
                    let optionDOM = $('<option value="'+ info[j].racetype +'">'+ info[j].racetype +'</option>');

                    selectDOM.append( optionDOM );
                }
                selectDOM.appendTo($('#projecttype'));
            }
        }
    }
    /******************************************************************/

});